package juc.cas;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

/*
*
* LongAddr 自增优化更快 原理：在竞争激烈的情况下会添加多个域进行自增(cell 数组) 减少cas循环重试次数
* 内部用到了 利用cas加锁的方式
* */
public class Test11 {
     AtomicInteger atomicInteger=new AtomicInteger(0);//无锁状态
     Long threadId;
    public static void main(String[] args) {
        Test11 test11 = new Test11();
        new Thread(()->{
            if (test11.lock()) {
                System.out.println("加锁成功1");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                test11.unlock();
            }else {
                System.out.println("加锁失败1");
            }
        }).start();
        new Thread(()->{
            if (test11.lock()) {
                System.out.println("加锁成功2");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                test11.unlock();
            }else {
                System.out.println("加锁失败2");
            }

        }).start();
    }
    public  boolean lock(){
        if(atomicInteger.compareAndSet(0,1)){
            threadId=Thread.currentThread().getId();
            return true;
        }
       return false;
    }
    public void unlock(){
        if(Thread.currentThread().getId()==threadId){
            atomicInteger.compareAndSet(1,0);
        }
    }
}
